﻿using Mono.Cecil;
using UnityEngine;
using UnityEngine.PlayerLoop;

namespace Util
{
    /// <summary>
    /// Unity静态单例对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class MonoSingleton<T>: MonoBehaviour where T: MonoSingleton<T>
    {
        protected MonoSingleton(){}
        private static T sIns;
        
        public static T Ins
        {
            get
            {
                //获得SingletonList对象
                var _SingletonList = GameObject.Find("SingletonList");
                if (!_SingletonList)
                {
                    _SingletonList = new GameObject("SingletonList");
                    DontDestroyOnLoad(_SingletonList);
                }
                
                
                //获得SingletonList下的指定单例对象
                var ins = GameObject.Find(typeof(T).Name);
                
                //不存在对象，创建对象并创建组件
                if (!ins)
                {
                    ins = new GameObject(typeof(T).Name);
                    sIns = ins.AddComponent<T>();
                    ins.transform.SetParent(_SingletonList.transform);
                    DontDestroyOnLoad(ins);
                    sIns.OnCreate();
                }

                if (!sIns)
                {
                    sIns = ins.AddComponent<T>();
                    sIns.OnCreate();
                }
                return sIns;
            }
        }
        /// <summary>
        /// 对内初始化接口
        /// </summary>
        protected virtual void OnCreate(){}
        
        /// <summary>
        /// 对外初始化接口
        /// </summary>
        public virtual void Init(){}

        /// <summary>
        /// 对外销毁接口
        /// </summary>
        public virtual void Release()
        { 
            Resources.UnloadAsset(sIns);
            sIns = null;
        }
    }
}